<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
$(document).ready(function(){

});

var x = "<?= $points; ?>";
var y = x.split('&');

for (var i = 0; i< y.length ; i++) {
  y[i] = y[i].split(',');
};
console.log(y);
var points = y;
var markers = [];
var map;


function initialize() {

  // Create an array of styles.
  var styles = [
    {
       stylers: [
        { hue: "#006652" },
        { saturation: -20 }
      ]
    },{
      featureType: "road",
      elementType: "geometry",
      stylers: [
        { lightness: 30 },
        { visibility: "simplified" }
      ]
    },{
      featureType: "road",
      elementType: "labels",
    }
  ];

  // Create a new StyledMapType object, passing it the array of styles,
  // as well as the name to be displayed on the map type control.
  var styledMap = new google.maps.StyledMapType(styles,
    {name: "Styled Map"});

  // Create a map object, and include the MapTypeId to add
  // to the map type control.
 var myLatlng = new google.maps.LatLng(14.586902, 120.98570599999994);
  var mapOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeControlOptions: {
      mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
    }
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);

   //Associate the styled map with the MapTypeId and set it to display.
  map.mapTypes.set('map_style', styledMap);
  map.setMapTypeId('map_style');

loadMap();

}

function loadMap() {
  addMarker();

google.maps.event.addListener(map, 'idle', function() {

    var bounds = map.getBounds();
    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();
    var nw = new google.maps.LatLng(ne.lat(), sw.lng());
    var se = new google.maps.LatLng(sw.lat(), ne.lng());

var mapCoords = [
    new google.maps.LatLng(nw.lat(), nw.lng()),
    new google.maps.LatLng(ne.lat(), ne.lng()),
    new google.maps.LatLng(se.lat(), se.lng()),
    new google.maps.LatLng(sw.lat(), sw.lng()),
  ];

 var mapView = new google.maps.Polygon({
    paths: mapCoords,
  });


  if (google.maps.geometry.poly.containsLocation(marker.position, mapView)) {
    
    document.getElementById("status").value = "Marker is within map";
    } 

    else {
    //codes to delete marker where marker's points is not within mapView
    document.getElementById("status").value = "Marker is not within map";

    }

    document.getElementById("ne").value = ne;
    document.getElementById("sw").value = sw;
    document.getElementById("nw").value = nw;
    document.getElementById("se").value = se;

    });
}

function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

function deleteMarkers() {
  clearMarkers();
  markers = [];
}

function addMarker() {

  var contentString = '<div id="content" class="search-plot large-12 column">'+
      '<div id="userimg" class="large-4 column">'+
      '<img src="img/user_dp/steve.jpg">'+
      '</div>'+
      '<div id="username" class="large-8 column">'+
      '<p id="inforWindowName" class="name"><?php echo ('Michael Jeuselle Yambao');?></p>'+
      '<div id="infoWindowSkills" style="margin-top:-10%;">'+
      '<p id="userskills" class="skills"><?php echo ('Php, Vb.net, CSS');?>' +'</p>'+
      '</div>'+
      '</div>' +
      '</div>';

  var infowindow = new google.maps.InfoWindow({
    maxWidth: 350,
    content: contentString
  });

  for( i = 0; i < points.length; i++ ) {

  var position = new google.maps.LatLng(points[i][1], points[i][2]);
  
  var marker = new google.maps.Marker({
    position: position,
    map: map,
    center: marker,
    icon: URL + 'img/icons/Marker.png',
    draggable: false,
    animation: google.maps.Animation.DROP
  });

   google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
            return function() {
              infowindow.open(map, marker);
            }
          })(marker, i));

   markers.push(marker);
   }

   map.setCenter(position);

}
      google.maps.event.addDomListener(window, 'load', initialize);

    </script>

<div class="row" style="margin-top:3rem;position:absolute;height:87%;">
	<div id="map-canvas" class="medium-4 large-4 column" style="padding:0;height:100%; margin-top:15px;">
	<!--<div>
	 Status:  <input type="text" id="status" size=40><br><br>
     Map top-left: <input type="text" id="nw" size=40><br>
     Map top-right: <input type="text" id="ne" size=40><br>
     Map bottom-right: <input type="text" id="se" size=40><br>
     Map bottom-left: <input type="text" id="sw" size=40></div>-->
	</div>

	<div class="medium-8 large-8 column" style="padding:2rem;overflow:auto;height:100%;">
		
		<div class="result-wrapper large-12 column">

      <?php if(sizeof($data) > 0) { foreach ($data as $value) { ?>
			<div class="search-grid medium-6 large-4 end column">
				<div class="search-result large-12 column">
					<div class="search-cover large-12 column" style="background:url(img/cover_photo/2.jpg);background-size:cover;">
						<div class="conbtn large-12 column">
              <?php if($this->session->get('user_id') != $value->user_id){ ?>
                <?php if(UserConnectionsTb::checkIfConnected($this->session->get('user_id'),$value->user_id)){ ?>
  							<a href="" class="tiny radius button">Connected</a>
                <?php }else{ ?> 
                  <?php if(!ConnectionRequestTb::findFirst(array(
                            "conditions"=> "sender_id = ?0 and receiver_id = ?1",
                            "bind" => array(0=>$this->session->get('user_id'),$value->user_id)
                      ))){ ?>
                      <a friend-id = "<?=$value->user_id?>" class="tiny button btnConnect" style="padding:.5rem;">Connect</a>
                      <?php }else { ?>
                      <a href="" class="tiny radius button">Requested</a>

                      <?php } ?> 
                <?php } ?>
              <?php } ?>
						</div>
						<div class="opac-search large-12 column">
							<div class="search-name medium-8 large-8 column">
								<h5><?= $value->fname.' '.$value->lname ?> </h5>
							</div>
							<div class="search-dp medium-2 large-2 column" style="background:url(<?= IMAGE_URL_SMALL.$value->profile_pic?>);background-size:cover;">	
							</div>
							<div class="medium-2 large-2 column"></div>
		
						</div>		
					</div>
					<div class="search-extra large-12 column">
						<?php if($value->city){ ?><p><i class="fa fa-map-marker"></i>&nbsp;<?= $value->city ?>, Philippines</p> <?php } ?>
						<p class="xy">
              <small>
              <?= UserAccountTb::getWorkExperience($value->work_experience,"work_description")?> .<?= UserConnectionsTb::countConnnections($value->user_id) ?> connections
              </small>
            </p>
					</div>
				</div>
			</div>
      <?php } } ?>

		</div> 
		<!-- <div class="text-center large-12 column">
			<a href="" class="button">Load more</a>
		</div> -->

		<!--<div class="medium-8 large-8 column" style="padding:2rem;overflow:auto;height:80vh;">
	 Status:  <input type="text" id="status" size=40><br><br>
     Map top-left: <input type="text" id="nw" size=40><br>
     Map top-right: <input type="text" id="ne" size=40><br>
     Map bottom-right: <input type="text" id="se" size=40><br>
     Map bottom-left: <input type="text" id="sw" size=40></div>
	</div>-->
</div>

<style>
.search-grid:hover {
 	cursor: -moz-zoom-in; 
    cursor: -webkit-zoom-in;
    cursor: zoom-in;	
}

</style>

<script type="text/javascript">
function insertRequest(friend_id)
  {
    var params = {};
    params.receiver_id = friend_id;
    return $.ajax({
      url: URL + 'connections/requestConnection',
      type: 'post',
      data: params,
      dataType: 'json'
    });
  }

  var $connect = $('.btnConnect');
  
  $connect.one('click',function(){
    
    var me = $(this);
    if(me.text() == "Connect" ){
      var friend_id = $(this).attr('friend-id');
      
      $(this).text('Sending . . .');
      
      insertRequest(friend_id).done(function(result){
        if(result.status == true)
        {

          me.text('Request Sent');
        }
        else
        {
          me.text(result.messages);
        }
      });
    }
  });
</script>


